﻿using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;

namespace MPSystem.Util
{
    /// <summary>
    /// 使用NPIO操作Excel的帮助类
    /// </summary>
    public class ExcelHelper
    {
        //private int insertRowIndex;
        //private int insertRowCount;
        //private Dictionary<int, string> insertData;

        #region 样式相关
        /// <summary>
        /// 样式字典，key为Workboo，value为默认样式
        /// </summary>
        private static Dictionary<HSSFWorkbook, HSSFCellStyle> _dic = new Dictionary<HSSFWorkbook, HSSFCellStyle>();
        /// <summary>
        /// 获取默认样式（将重置对默认样式的修改）
        /// </summary>
        /// <param name="workbook">工作表</param>
        /// <returns>默认样式</returns>
        public static HSSFCellStyle DefaultStyle(HSSFWorkbook workbook)
        {

            if (workbook == null)
                return null;
            HSSFCellStyle style = null;
            HSSFFont font = null;
            if (_dic.ContainsKey(workbook))
            {
                style = _dic[workbook];
                font = (HSSFFont)style.GetFont(workbook);
            }
            else
            {
                style = (HSSFCellStyle)workbook.CreateCellStyle();
                font = (HSSFFont)workbook.CreateFont();
                _dic.Add(workbook, style);
            }
            //font.FontName = fontname;
            font.FontHeightInPoints = 10;
            style.SetFont(font);

            style.BorderLeft = NPOI.SS.UserModel.BorderStyle.THIN;
            style.BorderRight = NPOI.SS.UserModel.BorderStyle.THIN;
            style.BorderTop = NPOI.SS.UserModel.BorderStyle.THIN;
            style.BorderBottom = NPOI.SS.UserModel.BorderStyle.THIN;
            style.Alignment = NPOI.SS.UserModel.HorizontalAlignment.CENTER;
            style.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.CENTER;
            return style;
        }
        #endregion

        #region 检测文件被占用 
        [DllImport("kernel32.dll")]
        public static extern IntPtr _lopen(string lpPathName, int iReadWrite);
        [DllImport("kernel32.dll")]
        public static extern bool CloseHandle(IntPtr hObject);
        public const int OF_READWRITE = 2;
        public const int OF_SHARE_DENY_NONE = 0x40;
        public static readonly IntPtr HFILE_ERROR = new IntPtr(-1);
        /// <summary>
        /// 检测文件是否可用
        /// </summary>
        /// <param name="FileNames">要检测的文件路径</param>
        /// <returns></returns>
        public static bool FileEditable(string FileNames)
        {
            if (!File.Exists(FileNames))
            {
                //文件不存在
                return true;
            }
            IntPtr vHandle = _lopen(FileNames, OF_READWRITE | OF_SHARE_DENY_NONE);
            if (vHandle == HFILE_ERROR)
            {
                //文件被占用
                return false;
            }
            //文件没被占用
            CloseHandle(vHandle);
            return true;
        }
        #endregion

        //插入
        public static void InsertRow(ISheet sheet, int insertRowIndex, int insertRowCount, IRow formatRow)
        {
            sheet.ShiftRows(insertRowIndex, sheet.LastRowNum, insertRowCount, true, false);
            for (int i = insertRowIndex; i < insertRowIndex + insertRowCount; i++)
            {
                IRow targetRow = null;
                ICell sourceCell = null;
                ICell targetCell = null;
                targetRow = sheet.CreateRow(i);
                for (int m = formatRow.FirstCellNum; m < formatRow.LastCellNum; m++)
                {
                    sourceCell = formatRow.GetCell(m);
                    if (sourceCell == null)
                    {
                        continue;
                    }
                    targetCell = targetRow.CreateCell(m);
                    targetCell.CellStyle = sourceCell.CellStyle;
                    targetCell.SetCellType(sourceCell.CellType);
                }
            }

            for (int i = insertRowIndex; i < insertRowIndex + insertRowCount; i++)
            {
                IRow firstTargetRow = sheet.GetRow(i);
                ICell firstSourceCell = null;
                ICell firstTargetCell = null;

                for (int m = formatRow.FirstCellNum; m < formatRow.LastCellNum; m++)
                {
                    firstSourceCell = formatRow.GetCell(m, MissingCellPolicy.CREATE_NULL_AS_BLANK);
                    if (firstSourceCell == null)
                    {
                        continue;
                    }
                    firstTargetCell = firstTargetRow.GetCell(m, MissingCellPolicy.CREATE_NULL_AS_BLANK);
                    firstTargetCell.CellStyle = firstSourceCell.CellStyle;
                    firstTargetCell.SetCellType(firstSourceCell.CellType);
                    //if (this.insertData != null && this.insertData.Count > 0)
                    //{
                    //    firstTargetCell.SetCellValue(insertData[m]);
                    //}
                    //firstTargetCell.SetCellValue("test");
                }
            }
        }
    }
}
